const fastify = require('fastify')()
const path = require('path')
const logger = require('./utils/logger')
const connectDB = require('./plugins/db')

const pkg = require('../package.json')
const { v1 } = require('./routes')
fastify.register(v1, { prefix: '/api/v1' })

fastify.register(require('@fastify/formbody'))
// 设置全局错误钩子
fastify.setErrorHandler(async (error, request, reply) => {
  const errorResponse = {
    code: reply.statusCode,
    message: error.message,
  }

  if (error.validation && error.validation.length > 0) {
    errorResponse.errors = error.validation.map((err) => ({
      message: err.message,
      path: err.dataPath, // 错误所在路径
    }))
    logger.error(errorResponse.errors, 1)
    return reply.status(400).send(errorResponse)
  }

  logger.error(error, 2)
  if (error.message === 'jwt expired') {
    errorResponse.message = 'token 过期！'
  } else {
    errorResponse.message = '服务器错误！'
  }
  return reply.status(500).send(errorResponse)
})

fastify.decorateReply('success', function (data) {
  return this.code(200).send({
    code: this.statusCode,
    ...data,
  })
})
fastify.decorateReply('fail', function (data) {
  return this.send(data)
})

// 注册静态文件服务
fastify.register(require('@fastify/static'), {
  root: path.join(__dirname, '../assets/images'),
  prefix: '/images/',
})

// 请求日志钩子
// fastify.addHook('onRequest', async (request, reply) => {
//   logger.info(`
//     请求方法： ${request.method}
//     请求地址： ${request.url}
//     Query 参数：${JSON.stringify(request.query)}
//     Body 参数：${request.body}
//   `)
// })

// 注册插件
fastify.register(require('@fastify/multipart'), {
  limits: {
    fileSize: 1000000,
  },
})

// fastify.register(statusCode)

// 启动服务器
const startServer = async () => {
  try {
    await connectDB()
    await fastify.listen({ port: 3000 })
    console.log(`******服务器启动成功，当前版本：${pkg.version}******`)
  } catch (err) {
    console.log(err)
    fastify.log.error(err)
    process.exit(1)
  }
}
startServer()
